#!/bin/bash

# to compute the coverage of mpfr-x.y.z, just copy this script
# into mpfr-x.y.z/tools and run it

# Warning! Do not run this script on a machine shared with other users,
# otherwise your account can easily be compromised:
#   https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21951
#
# To avoid being affected by this libtool bug, this script could be modified
# to use a subdirectory of /tmp/ompfr-gcov for the MPFR build.

# Set up the right directoy
cd $(dirname $0)/..

# First Build MPFR in /tmp/
echo "Erasing previous /tmp/ompfr-gcov"
rm -rf /tmp/ompfr-gcov || exit 1
mkdir /tmp/ompfr-gcov || exit 1

echo "Copying MPFR sources to /tmp/ompfr-gcov"
cp -r . /tmp/ompfr-gcov || exit 1
cd /tmp/ompfr-gcov || exit 1

echo "Remove previous coverage information."
rm -f $(find . -name '*.gc*')

# Remove MPFR_* environment variables to get reproducible coverage results.
for i in `env | sed -n 's/^\(MPFR_[^=]*\).*/\1/p'`; do unset "$i"; done

echo "Reconfiguring MPFR"
autoreconf -i || exit 1

echo "Building MPFR"
./configure --enable-assert=none --enable-tune-for-coverage --disable-shared --enable-static \
  CFLAGS="--coverage -g"  || exit 1
make clean  || exit 1
make all -j4 || exit 1

# Note: we want to compute the coverage even in case of failure of some tests.
unset GMP_CHECK_RANDOMIZE
make check -j4

# Check version of gcov:
# 3.3 outputs like this:
#  100.00% of 36 lines executed in function mpfr_add
#  100.00% of 36 lines executed in file add.c
#  Creating add.c.gcov.
# It doesn't support gcov *.c
#
# gcov (GCC) 3.4 outputs like this:
#  Function `mpfr_add'
#  Lines executed:100.00% of 36
#
#  File `add.c'
#  Lines executed:100.00% of 36
#  add.c:creating `add.c.gcov'
# It supports gcov *.c

# Setup the parser depending on gcov
version=$(gcov --version | head -1 | cut -f2 -d')')
version=$(( $(echo "$version" | cut -f1 -d'.')*100 + $(echo "$version" | cut -f1 -d'.')*10 ))
if test "$version" -ge 340 ; then
 echo "#!/bin/bash
while true ; do
 if read x ; then
 case \$x in
   Function*)
     read y
     case \$y in
      *100.00*)
       ;;
      *)
       echo \$x \$y
       ;;
     esac
     ;;
 esac
 else
   exit 0
 fi
done
" > coverage.subscript
else
 echo "#!/bin/bash
while true ; do
 if read x ; then
 case \$x in
   100.00*)
     ;;
   *function*)
     echo \$x
     ;;
 esac
 else
   exit 0
 fi
done
" > coverage.subscript
fi

# Do "gcov" for all files and parse the output
cd src
for i in $(find . -name '*.c')
do
    gcov -f $i -o $(dirname $i) 2> /dev/null || exit 1
done | bash ../coverage.subscript | grep -v '__gmp' > ../coverage.mpfr

rm -f coverage.subscript coverage-tmp || exit 1

cd -
lcov --rc lcov_branch_coverage=1 --capture --directory . --output-file all.info || exit 1
genhtml --branch-coverage -o coverage all.info || exit 1

echo "Coverage summary saved in file    /tmp/ompfr-gcov/coverage.mpfr"
echo "Detailed coverage is available at /tmp/ompfr-gcov/coverage/index.html"
